package fr.utbm.aiechat;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import fr.utbm.aiechat.packets.UserFileResponsePacket;

import android.os.AsyncTask;
import android.os.Environment;

public class FileSender extends AsyncTask<Void, Void, Void>
{
	private String filename;
	private DataInputStream reader;
	private long current;
	private long size;
	private InetAddress user;
	private boolean error = false;
	
	public FileSender(String filename, InetAddress user)
	{
		this.filename = filename;
		this.current = 0;
		this.user = user;
		
		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard, filename);
		
		System.out.println("Starting to send "+filename+" to "+user);
		
		if(!file.exists())
		{
			System.out.println("Can't send this file, it doesn't exist: "+filename);
			error = true;
		}
		
		size = file.length();
		
		try
		{
			reader = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	protected Void doInBackground(Void... arg0)
	{
		if(error)
			return null;
		
		byte[] buffer = new byte[1024];
		
		Socket s = null;
		DataOutputStream stream = null;
		try
		{
			s = new Socket(user, 6668);
			stream = new DataOutputStream(s.getOutputStream());
		}
		catch (IOException e1)
		{
			e1.printStackTrace();
		}
		
		
		if(s == null)
			return null;
		
		// then start the real upload.
		while(current < size)
		{			
			long length = 1024;
			
			if((size - current) < length)
				length = size - current;
			
			try
			{
				reader.read(buffer, 0, (int) length);
				
				UserFileResponsePacket packet = new UserFileResponsePacket(filename, length, buffer);
				
				stream.write(packet.getPacket());
				stream.flush();
				
				current += length;
				
				// this defines the throughput.
				Thread.sleep(10);
			}
			catch (Exception e)
			{
				e.printStackTrace();
				break;
			}
		}
		
		byte[] empty = new byte[1];
		UserFileResponsePacket packet = new UserFileResponsePacket(filename, 0, empty);
		try
		{
			stream.write(packet.getPacket());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		try
		{
			stream.close();
			s.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		return null;
	}

}
